package basicCode.sumArray;

import java.io.IOException;
import java.util.Random;
import java.util.Scanner;

public class SumArray {
    /*第一步 生成6个随机数的数组*/
    public int[] gennerateArray(int len){
        int[] arr=new int[len];
        for(int i=0; i<arr.length;i++){
            Random random = new Random();
            int x=random.nextInt(40)-15;
            arr[i] = x;
        }
        return arr;
    }

    /*核心算法*/
    public int maxsum(int[] arry){
        if(arry==null || arry.length==0){
            throw new IllegalArgumentException("数组不存在");
        }
        int result=arry[0],mark=0;

        for (int i = 0; i < arry.length; i++) {
            int temp = arry[i];
            if(mark>=0){
                mark+=temp;
            }else {
                mark=temp;
            }
            if(mark>result){
                result=mark;
            }
        }
        return result;
    }

    public static void main(String[] args) throws IOException {
        System.out.print("请输入生成数组的个数：");
        Scanner in =new Scanner(System.in);
        int n = in.nextInt();
        SumArray sumArray = new SumArray();
        int[] arr = sumArray.gennerateArray(n);
        /*打印生成的随机数*/
        System.out.print("[");
         for(int i=0; i<arr.length;i++){
             System.out.print(arr[i]+",");
         }
        System.out.println("]");

         /*求数组的最大子数组*/
        int maxsum = sumArray.maxsum(arr);
        System.out.println("最大值为:"+maxsum);
    }
}
